﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
public partial class JobManage_MateReceiptDetail : BasePage
{
    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    IJobHandler jobManage = new JobHandler();
    IBNTruckHandler truckManage = new BNTruckHandler();
    ISystemHandler systemManage = new SystemHandler();
    DataBase db = new DataBase();
    ISendTruckHandler sendTruckManage = new SendTruckHandler();
    ISyContainerModelHandler containerModelManage = new SyContainerModelHandler();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           
          // txtMateReceiptDate2.Text = DateTime.Now.ToString("yyyy-MM-dd");
            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "desc";

            ViewState["OrderByT"] = "PKID";
            ViewState["AccendingT"] = "desc";
            dataBind();
            dataBindDetail(int.Parse(Request["OrderID"]));
            dataBindTruck(GetClientID());
        }
    }

    public string GetClient(object id)
    {
        return systemManage.GetClient(id);
    }

    public string GetClientLinkMan(object id)
    {
        string name = string.Empty;
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@ClientID",id.ToString());
        string sqlStr = "select * from Sy_ClientLinkMan where ClientID=@ClientID";
        DataTable dt = clientManage.GetClientLinkManList(sqlStr, parms);
        if (dt != null && dt.Rows.Count > 0)
        {
            name = dt.Rows[0]["LinkMan"].ToString();
        }
        return name;
    }

    public string GetUserName(object userID)
    {
        return systemManage.GetUserName(userID);
    }

    public string GetDriver(object id)
    {
        return systemManage.GetDriver(id);
    }


    private void dataBind()
    {

        if (Session["UserID"] != null)
        {
            ISystemHandler sysManage = new SystemHandler();
            string strPermission = sysManage.GetLoginUserPermissions();
            if (!(strPermission.Contains("1071")))
            {
                Response.Redirect("~/NotPurview.aspx");
                return;
            }
            else
            {
                if (strPermission.Contains("1072"))
                {
                    BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(Request["OrderID"]));
                    if (orderQuery != null)
                    {
                        if (orderQuery.IsConfirmMateReceipt.ToString() == "0")//判断是否已经确认。如果未就显示确认按纽
                        {
                            btnConfirm.Visible = true;
                        }
                        else
                        {
                            btnConfirm.Visible = false;
                        }
                    }

                }
                else
                {
                    btnConfirm.Visible = false;
                }
            }
        }       
    }

    private void dataBindDetail(int orderID)
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@OrderID", orderID.ToString());
        string sqlStr = "select * from BN_ShippingOrderDtl where OrderID=@OrderID";
        DataTable dt = jobManage.GetShippingOrderDtl(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvShipperOrderDetailList.DataSource = view;
        gvShipperOrderDetailList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
            if (dt.Rows[0]["DeliveryDate"] != null && dt.Rows[0]["DeliveryDate"].ToString() != string.Empty)
            {
                txtDeliveryDate2.Text = DateTime.Parse(dt.Rows[0]["DeliveryDate"].ToString()).ToString("yyyy-MM-dd");
            }
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    private void dataBindTruck(int clientID)
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@OrderID", Request["OrderID"]);
        string sqlStr = @"select *,LicenseNO,(select Name from BN_Driver as T where T.PKID=BTDtl.Driver) as DriverName,
            (select CNShortName from Sy_Client as SC where SC.PKID=BT.Contractor) as ContractorName,
            (select OrderNO from BN_ShippingOrder as SO where SO.PKID=BT.OrderID) as OrderNO 
            from BN_SendTruck as BT,BN_SendTruckDtl as BTDtl,BN_Truck as T where BT.PKID=BTDtl.SendTruckID and T.PKID =BTDtl.TruckID and BT.OrderID=@OrderID";
        DataTable dt = sendTruckManage.GetList(sqlStr, parms);
        gvTruckList.DataSource = dt;
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderByT"] + " " + ViewState["AccendingT"];
        gvTruckList.DataSource = view;
        gvTruckList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotalTruck.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotalTruck.Text = "0";
        }
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvShipperOrderDetailList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvShipperOrderDetailList.PageCount)
            {
                this.gvShipperOrderDetailList.PageIndex = i;
                //数据绑定
                dataBindDetail(int.Parse(Request["OrderID"]));
            }
            else
            {
                // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
                Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);
                return;
            }
        }
        catch
        {
            // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
            Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvShipperOrderDetailList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBindDetail(int.Parse(Request["OrderID"]));
    }


    protected void gvShipperOrderDetailList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvShipperOrderDetailList.PageIndex = e.NewPageIndex;
        dataBindDetail(int.Parse(Request["OrderID"]));
    }
    protected void gvShipperOrderDetailList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBindDetail(int.Parse(Request["OrderID"]));
    }

    protected void lbtnGoTruck_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvTruckList.BottomPagerRow.FindControl("txtPagesTruck"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvTruckList.PageCount)
            {
                this.gvShipperOrderDetailList.PageIndex = i;
                //数据绑定
                dataBindTruck(GetClientID());
            }
            else
            {
                Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);
                return;
            }
        }
        catch
        {
            Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);

        }
    }
    protected void ddlPagesTruck_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvTruckList.PageSize = int.Parse(ddlPagesTruck.SelectedValue);
        dataBindTruck(GetClientID());
    }

    protected void gvTruckList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvTruckList.PageIndex = e.NewPageIndex;
        dataBindTruck(GetClientID());
    }
    protected void gvTruckList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderByT"].ToString().ToLower())
        {
            if (ViewState["AccendingT"].ToString().ToLower() == "asc")
            {
                ViewState["AccendingT"] = "desc";
            }
            else
            {
                ViewState["AccendingT"] = "asc";
            }
        }
        else
        {
            ViewState["OrderByT"] = e.SortExpression;
        }

        dataBindTruck(GetClientID());
    }

    private int GetClientID()
    {
        int clientID = 0;
        if (Session["UserID"] != null)
        {
            UsersQuery query = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
            if (query != null)
            {
                clientID = query.ClientID;
            }
        }
        return clientID;
    }

    public string GetType(object typeID)
    {
        string model = string.Empty;
        Sy_ContainerModelQuery query = containerModelManage.GetModel(int.Parse(typeID.ToString()));
        if (query != null)
        {
            return model = query.Model;
        }
        return model;
    }

    /// <summary>
    ///
    /// </summary>
    private void CloseSelect()
    {
        txtMateReceiptDate2.Text = DateTime.Now.ToString("yyyy-MM-dd");
        myDiv.Style.Add("display", "none");
        divError.Style.Add("display", "none");
    }


    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        myDiv.Style.Add("display", "block");
        divError.Style.Add("display", "block");
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("MateReceiptList.aspx");
    }

    //尾纸确认
    protected void btnSub_Click(object sender, EventArgs e)
    {
        if (txtMateReceiptDate2.Text != string.Empty)
        {
            SqlParameter[] parms = new SqlParameter[7];
            parms[0] = new SqlParameter("@OrderID", Request["OrderID"]);
            parms[1] = new SqlParameter("@IsConfirmMateReceipt", "1");//已确认
            parms[2] = new SqlParameter("@MateReceiptDate", txtMateReceiptDate2.Text.Trim());
            parms[3] = new SqlParameter("@MateReceiptConfirmUser", Session["UserID"].ToString());
            parms[4] = new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.MATECONFIRM.ToString("d"));
            parms[5] = new SqlParameter("@SOStatus", Enums.ShippingOrderStatus.MATECONFIRM.ToString("d"));
            parms[6] = new SqlParameter("@DeliveryDate", txtDeliveryDate2.Text.Trim());

            string sqlStr = "update BN_ShippingOrder set Status=@SOStatus,IsConfirmMateReceipt=@IsConfirmMateReceipt,MateReceiptDate=@MateReceiptDate,MateReceiptConfirmUser=@MateReceiptConfirmUser where PKID=@OrderID; ";
            sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,ReceiptDate=@MateReceiptDate,ReceiptUser=@MateReceiptConfirmUser,DeliveryDate=@DeliveryDate where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID));";
            sqlStr += "update BN_BookingDtl set DeliveryDate=@DeliveryDate where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID);";
            sqlStr += "update BN_ShippingOrderDtl set DeliveryDate=@DeliveryDate where OrderID=@OrderID;";

            if (db.ExecSqlTransaction(sqlStr, parms))
            {
                Jscript.Alert(Resources.Messages.MateReceiptConfirmSuccess, this.Page);
                CloseSelect();
                dataBind();
            }
            else
            {
                Jscript.Alert(Resources.Messages.MateReceiptConfirmFailed, this.Page);
            }
        }
        else
        {
            SqlParameter[] parms = new SqlParameter[2];
            parms[0] = new SqlParameter("@OrderID", Request["OrderID"]);
           // parms[1] = new SqlParameter("@IsConfirmMateReceipt", "1");//已确认
          //  parms[2] = new SqlParameter("@MateReceiptDate", txtMateReceiptDate2.Text.Trim());
           // parms[3] = new SqlParameter("@MateReceiptConfirmUser", Session["UserID"].ToString());
           // parms[4] = new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.MATECONFIRM.ToString("d"));
          //  parms[5] = new SqlParameter("@SOStatus", Enums.ShippingOrderStatus.MATECONFIRM.ToString("d"));
            parms[1] = new SqlParameter("@DeliveryDate", txtDeliveryDate2.Text.Trim());

            // sqlStr = "update BN_ShippingOrder set Status=@SOStatus,IsConfirmMateReceipt=@IsConfirmMateReceipt,MateReceiptDate=@MateReceiptDate,MateReceiptConfirmUser=@MateReceiptConfirmUser where PKID=@OrderID; ";
          string  sqlStr = "update BN_BookingNoteDtl set DeliveryDate=@DeliveryDate where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID));";
            sqlStr += "update BN_BookingDtl set DeliveryDate=@DeliveryDate where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID);";
            sqlStr += "update BN_ShippingOrderDtl set DeliveryDate=@DeliveryDate where OrderID=@OrderID;";

            if (db.ExecSqlTransaction(sqlStr, parms))
            {
                Jscript.Alert(Resources.Messages.DeliveryDateSuccess, this.Page);
                CloseSelect();
                dataBind();
            }
            else
            {
                Jscript.Alert(Resources.Messages.MateReceiptConfirmFailed, this.Page);
            }
            
        }
    }

    protected void btnClose_Click(object sender, EventArgs e)
    {
        CloseSelect();
    }
}
